import React, { Component } from 'react'

class AlterHeadShop extends Component {
    constructor() {
        super();
        this.state = {
            img: null,
            upRes:''
        }
    }

    handlerChange() {
        const that = this
        const file = document.getElementById('file').files[0]
        if (file.type !== 'image/jpeg') {
            alert('请上传jpg图片')
            return
        }
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = function (result) {
            that.setState({
                img: this.result,
                upRes:'',
            })
        }
    }

    update = ()=>{
        const that = this
        const file = document.getElementById('file').files[0]

        const formData = new FormData();
        formData.append('file',file);

        var id = JSON.parse(sessionStorage['user']).admin_id;

        fetch(`https:www.h5fd.xyz:2021/test/alterHeadShop/?id=${id}`,{
            method:'POST',
            body:formData,
        })
        .then(res=>res.json())
        .then(res=>{
            sessionStorage['user']=JSON.stringify(res);
            alert('修改成功')
            that.setState({
                img:null,
                upRes:'success'
            })
            window.location.reload();
        })
    }

    render() {
        return (
            <div>
                <h2>修改头像</h2>
                <input className="file" type="file" id="file" accept="image/*" onChange={this.handlerChange.bind(this)} />
                {
                    this.state.img ?
                        <div>
                            <img src={this.state.img} alt="" style={{ width: '100px' }} />
                            <button onClick={this.update.bind(this)}>上传</button>
                        </div>
                        : <></>
                }
            </div>
        )
    }
}

export default AlterHeadShop;